/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tfb.web.controller;

import com.tfb.rong.Users;
import com.tfb.service.UserAssessmentI;
import com.tfb.service.utility.AppConst;
import com.tfb.service.utility.HttpUtil;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class WeChatAuthorityFilter implements Filter, AppConst {

    private UserAssessmentI daoService;
    private String[] byPassKeywords;
    private String mockCode;
    static Log log = LogFactory.getLog(WeChatAuthorityFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        daoService = (UserAssessmentI) ac.getBean("userAssessmentService");
        mockCode = filterConfig.getInitParameter("mockCode");
        byPassKeywords = filterConfig.getInitParameter("by.pass.authen.pattern").split(",");
        for (int i = 0; i < byPassKeywords.length; ++i) {
            byPassKeywords[i] = byPassKeywords[i].trim();
        }
    }

    private boolean isByPass(String URI) {
        for (String keyword : byPassKeywords) {
            if (URI.endsWith(keyword)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String code = httpRequest.getParameter("code");
        log.info("the code is " + code);
        String requestURI = httpRequest.getRequestURI();
        log.info("request:" + requestURI);
        if (isByPass(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        boolean isMockCode = false;
        if (mockCode != null && !mockCode.isEmpty()) {
            code = mockCode;
            isMockCode = true;
        }
        if (code != null && !code.isEmpty()) {
            // From Wechat menu, get open_id and check if it is a member of TLR
            // if user id == null, try to login
            String openID = isMockCode ? code : HttpUtil.getWechatOpenID(code);
            if (openID == null) {
                RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/not_back.html");
                dispatcher.forward(request, response);
                return;
            }
            httpResponse.addCookie(new Cookie(USER_OPEN_ID, openID));
            Users user = daoService.selectUserInfo(openID);
            if (user != null && user.getStatus() == 1) {
                // Ok to login, save user info into session
                httpRequest.getSession().setAttribute(USER_OPEN_ID, openID);
                httpRequest.getSession().setAttribute(USER_DB_ID, user.getId());
                httpResponse.addCookie(new Cookie(USER_DB_ID, user.getId()));
                String requestURI2 = httpRequest.getRequestURI();
                if (requestURI2.contains("devices.html") && user.getType() != 1) {
                    RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/not_customer.html");
                    dispatcher.forward(request, response);
                } else if (requestURI2.contains("users.html") && user.getType() == 1) {
                    RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/customers.html");
                    dispatcher.forward(request, response);
                } else if (requestURI2.contains("users.html") && (user.getType() == 2 || user.getType() == 3)) {
                    RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/employees.html");
                    dispatcher.forward(request, response);
                } else {
                    chain.doFilter(request, response);
                }
            } else if (user != null && user.getStatus() == 2) {
                RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/user_lock.html");
                dispatcher.forward(request, response);
            } else {
                // Login fail, forward to register page
                httpResponse.addCookie(new Cookie(TARGET_NAME, requestURI));
                RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/register.html");
                dispatcher.forward(request, response);
            }
        } else {
            String userDBID = httpRequest.getSession().getAttribute(USER_DB_ID) != null
                              ? httpRequest.getSession().getAttribute(USER_DB_ID).toString() : HttpUtil.getCookieUserDBID(httpRequest);
            // check cookie and user id in session, if no such info, forward to register page
            if (userDBID == null) {
                String target = httpRequest.getParameter("target");
                log.info("target: " + target);
                httpResponse.addCookie(new Cookie(TARGET_NAME, target));
                RequestDispatcher dispatcher = httpRequest.getServletContext().getRequestDispatcher("/register.html");
                dispatcher.forward(request, response);
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
    }

}
